// @ts-ignore
import { spawnSync } from 'child_process'
// @ts-ignore
import fs from 'fs';
import md5 from '../encryption/md5';

export default (path:string,dir=""):any=>{
    //文件md5 folder父级文件夹
    let md,folder=dir,tsstaue:any={};
    //获取这个文件的md5
    try{
        if(dir!==""){
            if(!fs.existsSync(dir)){
                fs.mkdirSync(dir);
                fs.writeFileSync(dir+"/ts.json",'{}')
            }else {
                md = getFileMd5(path);
                //获取一下验证文件
                // @ts-ignore
                tsstaue = require(dir+"/ts.json");
                //判断一下ts需不需要重新编译
                if(tsstaue[path]===md){return ''}
                tsstaue[path]=md;
            }
            dir="--outDir "+dir
        }
        console.log("开始编译",path);
        let data = spawnSync("cmd.exe",["/c",`tsc ${dir} --target es6 ${path}`])?.output.toString();
        //没错误就记录一下md5
        if(!data.includes("err")){
            console.log("编译成功"+path)
            fs.writeFileSync(folder+"/ts.json",JSON.stringify(tsstaue))
        }
        return data.substring(1,data.length-1);
    }catch (err){
        console.log(err);
    }
}

//获取文件的md5
function getFileMd5(path:string){
   return md5(fs.readFileSync(path,'utf8'))
}